package vip.web3.api.controller;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import vip.web3.api.annotation.Login;
import vip.web3.api.annotation.NoLogin;
import vip.web3.api.dao.biz.UserDao;
import vip.web3.api.entity.biz.UserEntity;
import vip.web3.api.form.user.AuthApplyForm;
import vip.web3.api.form.user.EditForm;
import vip.web3.api.form.user.LoginForm;
import vip.web3.api.form.user.RegisterForm;
import vip.web3.api.mapper.UserMapper;
import vip.web3.api.service.base.ApiFileUploadService;
import vip.web3.api.service.base.SysConfigApiService;
import vip.web3.api.service.biz.UserService;
import vip.web3.api.vo.biz.AlloyVo;
import vip.web3.api.vo.biz.InviteUserVo;
import vip.web3.api.vo.biz.TeamInfoVo;
import vip.web3.api.vo.biz.UserInfoVo;
import vip.web3.common.enums.user.PwdTypeEnum;
import vip.web3.common.exception.RRException;
import vip.web3.common.utils.PatternUtils;
import vip.web3.common.utils.R;
import vip.web3.common.utils.Servlets;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserApi {

    @Autowired
    private UserDao userDao;

    @Autowired
    private UserService userService;

    @Resource
    private ApiFileUploadService apiFileUploadService;

    @Resource
    private SysConfigApiService sysConfigApiService;

    @NoLogin
    @PostMapping("/register")
    public R register(@Valid @RequestBody RegisterForm form) {
        log.info("注册开始 form={}", form);

        if (!form.getPassword().equals(form.getConfirmPassword())) {
            return R.error(-1, "登录密码输入不一致");
        }
        if (!form.getFundPassword().equals(form.getConfirmFundPassword())) {
            return R.error(-1, "资金密码输入不一致");
        }
        boolean result = PatternUtils.matchPassword(form.getPassword());
        if (!result) {
            return R.error(-1, "密码必须是8-16位,字母+数字组合");
        }

        boolean resultFund = PatternUtils.pureNumbers(form.getFundPassword());
        if (!resultFund || form.getFundPassword().length() != 6) {
            return R.error(-1, "资金密码必须是6位纯数字");
        }

        boolean resultMobile = PatternUtils.pureMobile(form.getMobile());
        if (!resultMobile) {
            return R.error(-1, "错误手机号");
        }

        UserEntity entity = UserMapper.INSTANCE.toUserEntity(form);
        String account = userService.register(entity);
        return R.ok().put("data", account);
    }

    @NoLogin
    @PostMapping("/login")
    public R login(@Valid @RequestBody LoginForm form) {
        log.info("登录开始 form={}", form);
        String token = userService.login(form);
        return R.ok().put("data", token);
    }


    @Login
    @PostMapping("/logout")
    public R logout() {
        userService.logout();
        return R.ok();
    }

    @Login
    @PostMapping("/authApply")
    public R authApply(@Valid @RequestBody AuthApplyForm form) {
        String idNo = form.getIdNo();
        boolean result = PatternUtils.matchId(idNo);
        if (!result) {
            return R.error(-1, "身份证号码错误!");
        }
        userService.authApply(form);
        return R.ok();
    }

    @Login
    @PostMapping("/edit")
    public R edit(@Valid @RequestBody EditForm form) {
        if(form.getType().intValue() <= 3){
            // 昵称 性别 头像
            UserEntity userEntity = this.userService.getById(Servlets.getUserId());
            if (!DigestUtils.sha256Hex(form.getPassword()).equals(userEntity.getPassword())) {
                throw new RRException("登录密码错误!", -1);
            }
            userService.edit(form);
        } else if (form.getType().intValue() == 4) {
            // 手机
            boolean resultMobile = PatternUtils.pureMobile(form.getMobile());
            if (!resultMobile) {
                return R.error(-1, "错误手机号!");
            }
            userService.updateMobile(form);
        } else {
            if (!form.getPassword().equals(form.getConfirmPassword())) {
                return R.error(-1, "密码输入不一致!");
            }
            // 5 密码
            if (PwdTypeEnum.PWD.equals(PwdTypeEnum.get(form.getType()))) {
                boolean result = PatternUtils.matchPassword(form.getPassword());
                if (!result) {
                    return R.error(-1, "密码必须是8-16位,字母+数字组合");
                }
            } else {
                // 6支付密码
                boolean resultFund = PatternUtils.pureNumbers(form.getPassword());
                if (!resultFund || form.getPassword().length() != 6) {
                    return R.error(-1, "资金密码必须是6位纯数字");
                }
            }
            userService.updatePwd(form);
        }

        return R.ok();
    }

    @Login
    @GetMapping("/info")
    public R info() {
        UserInfoVo userInfoVo = this.userService.info();
        userInfoVo.setInvestment(sysConfigApiService.getValue("alloy:investment:url:1"));
        userInfoVo.setGender(Integer.valueOf(sysConfigApiService.getValue("alloy:app:update:version")));
        String value = sysConfigApiService.getValue("alloy:app:bsc:usdt:recharge");
        if("0".equals(value)){
            userInfoVo.setBscAddress("暂未开启充值!");
        }
        String notice = sysConfigApiService.getValue("alloy:app:index:notice");
        userInfoVo.setNotice(notice);

        return R.ok().put("data", userInfoVo);
    }

    @NoLogin
    @RequestMapping("/download")
    public R download() {
        return R.ok().put("data", sysConfigApiService.getValue("alloy:sys:register:url"));
    }

    @Login
    @GetMapping("/alloy")
    public R alloy() {
        AlloyVo vo = new AlloyVo();
        String value1 = sysConfigApiService.getValue("alloy:alloy:number:1");
        String value2 = sysConfigApiService.getValue("alloy:alloy:number:2");
        String value3 = sysConfigApiService.getValue("alloy:alloy:number:3");
        String value4 = sysConfigApiService.getValue("alloy:alloy:number:4");
        String value5 = sysConfigApiService.getValue("alloy:alloy:number:5");
        vo.setAlloy1(Integer.valueOf(value1));
        vo.setAlloy2(Integer.valueOf(value2));
        vo.setAlloy3(Integer.valueOf(value3));
        vo.setAlloy4(Integer.valueOf(value4));
        vo.setAlloy5(Integer.valueOf(value5));
        vo.setUser1(0);
        vo.setUser2(0);
        vo.setUser3(0);
        vo.setUser4(0);
        vo.setUser5(0);
        return R.ok().put("data", vo);
    }

    @Login
    @GetMapping("/invite/records/{level}")
    public R inviteRecords(@PathVariable Integer level) {
        List<InviteUserVo> list = this.userService.listInvite(level);
        if(!CollectionUtils.isEmpty(list)){
            for (InviteUserVo vo : list) {
                vo.setMobile("****" + vo.getMobile().substring(6));
                vo.setNick("****" + vo.getMobile().substring(6));
            }
        }
        return R.ok().put("data", list);
    }

    @Login
    @GetMapping("/team/info")
    public R teamInfo() {
        TeamInfoVo userInfoVo = this.userService.teamInfo();
        return R.ok().put("data", userInfoVo);
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        R uploadFile = apiFileUploadService.uploadFile(file);
        return R.ok().put("data", uploadFile.get("dirPath"));
    }

    /**
     * 文件上传
     */
    @PostMapping("/upload/base64")
    public R uploadBase64(String file) {
        R uploadFile = apiFileUploadService.uploadBase64(file);
        return R.ok().put("data", uploadFile.get("dirPath"));
    }
}
